<template>
  <div class="div-main" style="width: 100%; min-height: 86vh">
    <el-page-header @back="goBack" content="火车车次信息" style="margin-bottom: 10px;">
    </el-page-header>
    <el-divider></el-divider>
    <el-collapse-transition>
      <div v-if="show === 0">
        <div style="display: flex; display: flex; align-items: center; flex-direction: row;">
          <el-input placeholder="请输入关键字(名字)" style="width: 200px; margin-left: 30px;" v-model="search">
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
          <el-button type="primary" plain style="margin-left: 20px;" :loading="searchLoading"
            @click="setgetTrain">查询</el-button>
          <el-button type="danger" plain @click="openAddTrainNumber">增加</el-button>
        </div>
        <div style="margin-left: 30px; margin-top: 20px;">
          <el-table height=388 style=" width: 98%; " stripe border :data="tableData"
            :header-cell-style="{ background: '#F0F8FF', color: '#5E5F61', textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }">
            <el-table-column type="index" width="80" label="序号">
            </el-table-column>
            <el-table-column prop="trainNumberName" width="130" label="车次">
            </el-table-column>
            <el-table-column prop="startDate" label="开始日期" width=150>
              <template>

              </template>
            </el-table-column>
            <el-table-column prop="endDate" label="结束日期" width=150>
            </el-table-column>
            <el-table-column prop="stationStart" label="起始车站-(起始时间)">
              <template slot-scope="scope">
                <div style="font-weight: bold;">{{ scope.row.stationStart }}-({{ scope.row.startTime }})</div>
              </template>
            </el-table-column>
            <el-table-column prop="stationEnd" label="终到车站-(终到时间)">
              <template slot-scope="scope">
                <div style="font-weight: bold;">{{ scope.row.stationEnd }}-({{ scope.row.endTime }})</div>
              </template>
            </el-table-column>
            <el-table-column prop="trainType" label="火车类型" width=120>
            </el-table-column>
            <el-table-column prop="sequence" label="方向" width=120>
              <template slot-scope="scope">
                <el-tag v-if="scope.row.sequence === -1" type="success">进京</el-tag>
                <el-tag v-if="scope.row.sequence === 1" type="danger">出京</el-tag>
              </template>
            </el-table-column>

            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- <el-button type="primary" icon="el-icon-edit" size="small" style="margin-right: 10px;"></el-button> -->
                <el-popconfirm title="确定删除吗？" @confirm="deleteTrainNumber(scope.row)">
                  <el-button type="danger" icon="el-icon-delete" size="small" slot="reference"></el-button>
                </el-popconfirm>

              </template>
            </el-table-column>
          </el-table>
        </div>
        <div style="text-align: center; margin-top: 30px;">
          <el-pagination @current-change="handleCurrentChange" layout="total, prev, pager, next, jumper" :total=page.total
            :page-size=page.pageSize :current-page.sync=page.currentPage>
          </el-pagination>
        </div>
      </div>
    </el-collapse-transition>
    <el-collapse-transition>
      <div v-if="show === 1">
        <p style="margin-left: 60px; font-weight: bold;margin-bottom: 20px;">添加火车车次</p>
        <div style="display: flex;">
          <div>
            <el-form label-width="150px" :model="addTraiNumber" :rules="rulesAddTrainNumber" ref="addTraiNumber">
              <el-form-item label="车次：" prop="trainNumberName">
                <el-input style="width:200px" v-model="addTraiNumber.trainNumberName" placeholder="请输入车次"></el-input>
              </el-form-item>
              <el-form-item label="火车类型：" prop="trainType">
                <el-select placeholder="请选择火车类型" style="width:200px" filterable clearable
                  v-model="addTraiNumber.trainType">
                  <el-option v-for="item in trainOptions" :key="item.trainName" :label="item.trainName"
                    :value="item.trainName">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="方向：" prop="sequence">
                <el-radio-group v-model="addTraiNumber.sequence" placeholder="请选择火车方向">
                  <el-radio :label="-1"><el-tag type="success">进京</el-tag></el-radio>
                  <el-radio :label="1"><el-tag type="danger">出京</el-tag></el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="开始日期：" prop="startDate">
                <el-date-picker placeholder="选择开始日期" style="width: 200px;"
                  v-model="addTraiNumber.startDate"></el-date-picker>
              </el-form-item>
              <el-form-item label="起始时间：" prop="startTime">
                <el-time-picker placeholder="选择起始时间" style="width: 200px;" type="time" format='HH:mm' value-format='HH:mm'
                  v-model="addTraiNumber.startTime"></el-time-picker>
              </el-form-item>
            </el-form>
            <el-row style="margin-left: 150px; margin-top: 50px;">
              <el-button @click="cancelAddTrainNumber">取消</el-button>
              <el-button type="primary" @click="setAddTrainNumber" :loading="addLoading">确认</el-button>
            </el-row>
          </div>
          <div style="margin-left: 100px; width:500px">
            <!-- <p style="margin-left: 60px; font-weight: bold;margin-bottom: 20px;">添加经停站</p> -->
            <el-form label-width="100px" :model="addTraiNumber" :rules="rulesAddTrainNumber" ref="addTrainNumber">
              <el-form-item label="起始站：" prop="stationStart">
                <el-select placeholder="请选择起始站" style="width:200px" filterable clearable
                  v-model="addTraiNumber.stationStart">
                  <el-option v-for="item in stationOptions" :key="item.id" :label="item.stationName" :value="item.id">
                  </el-option>
                </el-select>
                <el-button @click.prevent="addDomain()" circle icon="el-icon-plus" type="primary" size="mini"
                  style="margin-left: 10px;" plain></el-button>
              </el-form-item>
              <div style=" max-height:310px; overflow-y:auto; ">
                <el-form-item v-for="(domain, index) in addTraiNumber.stations" :label="'第' + (index + 1) + '站：'"
                  :key="domain.key" width="200px">
                  <el-select placeholder="请选择经停站" style="width:200px" filterable clearable v-model="domain.stationName">
                    <el-option v-for="item in stationOptions" :key="item.stationName" :label="item.stationName"
                      :value="item.stationName">
                    </el-option>
                  </el-select>
                  <el-input v-model="domain.stopTime" style="width: 70px; margin-left: 20px; "></el-input>
                  <el-button @click.prevent="removeDomain(domain)" circle icon="el-icon-minus" type="danger" size="mini"
                    style="margin-left: 10px; margin-right: 10px;" plain></el-button>
                </el-form-item>
              </div>
              <el-form-item label="终点站：" prop="stationEnd">
                <el-select placeholder="请选择终点站" style="width:200px" filterable clearable
                  v-model="addTraiNumber.stationEnd">
                  <el-option v-for="item in stationOptions" :key="item.id" :label="item.stationName" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </el-collapse-transition>
  </div>
</template>

<script>
export default {
  name: "trainNumber",
  data() {
    return {
      page: {
        total: 0,
        pageSize: 6,
        currentPage: 1
      },
      listdata: [],
      show: 0,
      // 模糊查询
      search: '',
      searchLoading: false,

      // 增加车次
      trainOptions: [],
      stationOptions: [],
      addLoading: false,
      addTraiNumber: {
        trainNumberName: '',
        startTime: '',
        stationStart: '',
        stationEnd: '',
        trainType: '',
        startDate: '',
        sequence: '',
        stationNumber: '',
        stations: [{
          stationName: '',
          stopTime: ''
        }],
      },
      rulesAddTrainNumber: {
        trainNumberName: [
          { required: true, message: '请输入车次', trigger: ['blur', 'change'] },
        ],
        trainType: [
          { required: true, message: '请选择火车类型', trigger: ['blur', 'change'] },
        ],
        startDate: [
          { type: 'date', required: true, message: '选择开始日期', trigger: ['blur', 'change'] },
        ],
        startTime: [
          { required: true, message: '请选择起始时间', trigger: ['blur', 'change'] },
        ],
        sequence: [
          { required: true, message: '请选择火车方向', trigger: ['blur', 'change'] },
        ],
        stationStart: [
          { required: true, message: '请选择起始站', trigger: ['blur', 'change'] },
        ],
        stationEnd: [
          { required: true, message: '请选择起始站', trigger: ['blur', 'change'] },
        ],
        stationName: [
          { required: true, message: '请选择经停站', trigger: ['blur', 'change'] },
        ],
        stopTime: [
          { required: true, message: '请输入经停时间', trigger: ['blur', 'change'] },
        ]
      },
      // trainNumber: {
      //   trainNumberName: '',
      //   startTime: '',
      //   stationStart: '',
      //   stationEnd: '',
      //   trainType: '',
      //   startDate: '',
      //   sequence: '',
      // },
      // trainNumberStations: [],
    }
  },
  methods: {
    goBack() {
      this.$router.push({ name: "adminHome" })
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val
      this.getTrainNumberPage()
    },
    // 根据分页
    getTrainNumberPage() {
      this.request.get("/trainNumber/getAllTrainNumberByPage/" + this.page.pageSize + "/" + this.page.currentPage).then(
        response => {
          if (response.data.code === 1) {
            this.listdata = response.data.data.records
            this.page.total = response.data.data.total
            console.log(this.listdata);
            this.$message({
              message: '更新页面成功！',
              type: 'success',
              duration: 1000
            });
          } else {
            this.$message({
              message: '更新页面失败！',
              type: 'info',
              duration: 1000
            });
          }
        },
        error => {
          console.log(error)
        }
      )
    },
    // 模糊分页查询
    setgetTrain() {
      this.searchLoading = true
      setTimeout(() =>
        this.getTrainNumber(), 1000
      )
    },
    getTrainNumber() {
      if (this.search != '') {
        this.request.get("/trainNumber/getTrainNumberByPage/" + this.page.pageSize + "/" + this.page.currentPage + "/" + this.search).then(
          response => {
            if (response.data.code === 1) {
              this.listdata = response.data.data.records
              this.page.total = response.data.data.total
              this.$message({
                message: '更新页面成功！',
                type: 'success',
                duration: 1000
              });
            } else {
              this.$message({
                message: '更新页面失败！',
                type: 'info',
                duration: 1000
              });
            }
          },
          error => {
            console.log(error)
          }
        ).finally(() => {
          this.searchLoading = false
        })
      } else {
        this.getTrainNumberPage()
        this.searchLoading = false
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //增加车次 
    removeDomain(item) {
      var index = this.addTraiNumber.stations.indexOf(item)
      if (index !== -1) {
        this.addTraiNumber.stations.splice(index, 1)
      }
    },
    addDomain() {
      this.addTraiNumber.stations.push({
        value: '',
        key: Date.now()
      });
    },
    getAlltrain() {
      this.request.get("/train/getAllTrain").then(
        response => {
          if (response.data.code === 1) {
            this.trainOptions = response.data.data
          }
        },
        error => {
          console.log(error)
        }
      )
    },
    getAllStation() {
      this.request.get("/station/getAllStation").then(
        response => {
          if (response.data.code === 1) {
            this.stationOptions = response.data.data
          }
        },
        error => {
          console.log(error)
        }
      )
    },

    openAddTrainNumber() {
      this.show = 1
      this.getAlltrain()
      this.getAllStation()
    },
    cancelAddTrainNumber() {
      this.show = 0
      this.resetForm('addTraiNumber')
      this.addTraiNumber.stations = [{
        stationName: '',
        stopTime: ''
      }]
      this.addTraiNumber.stationStart = ''
      this.addTraiNumber.stationEnd = ''
    },

    setAddTrainNumber() {
      this.addLoading = true
      // this.assemblyTrainNumber()
      setTimeout(() =>
        this.addTrainNumber()
        , 1000)
    },

    addTrainNumber() {
      console.log(this.addTraiNumber);
      console.log(this.trainNumber);
      this.addTraiNumber.stationNumber = this.addTraiNumber.stations.length + 2
      this.request.post("/trainNumber/addTrainNumber/", this.addTraiNumber).then(
        response => {
          if (response.data.code === 1) {
            this.$message({
              message: '添加成功！',
              type: 'success',
              duration: 1000
            });
            if (this.search != '') {
              this.getrainNumber()
            } else {
              this.getTrainNumberPage()
            }
            this.cancelAddTrainNumber()
          } else {
            this.$message({
              message: '添加失败！',
              type: 'error',
              duration: 1000
            });
          }
        },
        error => {
          console.log(error)
        }
      ).finally(() => {
        this.addLoading = false
      })
    },
    // 删除列车
    deleteTrainNumber(row) {
      this.request.delete("/trainNumber/deleteTrainNumber/" + row.id + "/" + row.trainNumberName).then(
        response => {
          if (response.data.code === 1) {
            this.$message({
              message: '删除成功！',
              type: 'success',
              duration: 1000
            });
            if (this.search != '') {
              this.getTrainNumber()
            } else {
              this.getTrainNumberPage()
            }
          } else {
            this.$message({
              message: '删除失败！',
              type: 'error',
              duration: 1000
            });
          }
        },
        error => {
          console.log(error)
        }
      )
    }
  },
  created() {
    this.getTrainNumberPage()
  },
  computed: {
    tableData() {
      return this.listdata
    }
  }
}

</script>

<style scoped>
.div-main {
  width: 100%;
  min-height: 86vh
}

::v-deep .el-select-dropdown__list {
  height: 160px;
}
</style>